package com.kiln.juxingqs

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import client.global.commlib.BaseApplication
import client.global.commlib.ContextProvider
import client.global.commlib.SimpleLifecycleCallbacks
import client.global.commlib.base.FinishReciver
import client.global.commlib.utils.SharedUtil
import com.kiln.juxingqs.ui.LoginActivity
import com.kiln.juxingqs.utils.AppConfig
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.ocr.sdk.common.OcrModeType
import com.tencent.ocr.sdk.common.OcrSDKConfig
import com.tencent.ocr.sdk.common.OcrSDKKit
import com.tencent.ocr.sdk.common.OcrType

class MyApp : BaseApplication() {

    override fun onCreate() {
        super.onCreate()
        registerLifecycle()
        initSdk(this)

//        AppCompatDelegate.setDefaultNightMode(if(SharedUtil.read("isNight",false)) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO)

    }

    companion object {
        const val TAG = "logbd"//

        fun initSdk(application: Application) {
            // Bugly 异常捕捉
            CrashReport.initCrashReport(application, AppConfig.getBuglyId(), AppConfig.isDebug())
        }
    }


    private fun registerLifecycle() {
        registerActivityLifecycleCallbacks(object : SimpleLifecycleCallbacks() {

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

                if (activity is AppCompatActivity)
                    ContextProvider.get().attach(activity as AppCompatActivity, {
                        SharedUtil.clear("token")
                        it?.let {
                            it.startActivity(Intent(it, LoginActivity::class.java))
                            activity.sendBroadcast(Intent(FinishReciver.FINISH_ACTION))
                        }
                    })
            }

            override fun onActivityResumed(activity: Activity) {
                Log.d("MyApp", activity.localClassName)
                if (activity is AppCompatActivity)
                    ContextProvider.get().attach(activity as AppCompatActivity, {
                        SharedUtil.clear("token")
                        it?.let {
                            it.startActivity(Intent(it, LoginActivity::class.java))
                            activity.sendBroadcast(Intent(FinishReciver.FINISH_ACTION))
                        }
                    })
            }

            override fun onActivityStopped(activity: Activity) {}

            override fun onActivityDestroyed(activity: Activity) {
                //                ContextProvider.get().detach()
            }
        })
    }
}